package org.neframework.webtest.action.database;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.neframework.webtest.util.config.Config;
import org.neframework.webtest.util.data.DbTools;
import org.neframework.webtest.util.file.FileTools;
import org.neframework.webtest.util.file.ZipTools;

import org.neframework.webtest.base.BaseController;
import com.tmsps.neframework.mvc.annotation.Controller;
import com.tmsps.neframework.mvc.annotation.RequestMapping;
import com.tmsps.neframework.mvc.annotation.ResponseBody;
import com.tmsps.neframework.mvc.plugin.Tip;

@Controller
@RequestMapping("/cp/database")
public class DatabaseRestoreController extends BaseController {

	@RequestMapping("/restore_all")
	@ResponseBody
	public void restore_all() throws FileUploadException {
		resp.setCharacterEncoding("utf-8");

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = req.getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		List<FileItem> items = upload.parseRequest(req);
		Iterator<FileItem> iter = items.iterator();

		File importFile = null;
		File dataFolder = new File(Config.getConfig().DATA_PATH);
		File outPath = dataFolder.getParentFile();
		while (iter.hasNext()) {
			FileItem item = iter.next();
			if (item.isFormField()) {
				// 非文件上传字段
				continue;
			} else {
				importFile = FileTools.processUploadedFile(item, outPath);
			}
		}
		if (importFile == null) {
			this.setTipMsg(false, "还原失败-->上传失败!", Tip.Type.error);
			return;
		}
		// 不删除旧的文件夹
		// dataFolder.delete();
		// 解压新上传的 zip 文件
		ZipTools.unzip(importFile);
		// 还原 DB
		DbTools.restore();

		this.setTipMsg(true, "还原成功!请退出重新登录!", Tip.Type.success);
	}
}
